package com.hsc.mvc.handler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author
 * @date 2025-06-10
 * @Description 转发携带数据的处理器
 */
public class ModelAndViewHandler implements ResponseHandleStrategy {
    @Override
    public boolean isSupport(Object result, Method targetMethod) {
        return result instanceof ModelAndView;
    }

    @Override
    public void handle(Object result, Method targetMethod, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取ModelAndView 对象
        ModelAndView modelAndView = (ModelAndView) result;
        // 获取所有需要转发时携带的参数
        Set<String> attributeNames = modelAndView.getAttributeNames();
        for (String attributeName : attributeNames) {
            // 设置打请求对象中
            request.setAttribute(attributeName, modelAndView.getAttribute(attributeName));
        }
        // 携带参数进行转发
        String viewName = modelAndView.getViewName();
        request.getRequestDispatcher(viewName).forward(request, response);
    }
}
